<?php
namespace app\adminapiv3\service;

/**
 * @name: ssh 连接
 * @Param: 
 * @Description: 
 * @Author: foo
 * @Date: 2019-10-29 15:21:00
 */
class SSH extends Base
{
    public $conn;
    function __construct($ip, $user, $pwd, $port = 22)
    {
        $this->conn = @ssh2_connect($ip, $port);
        if(!@ssh2_auth_password($this->conn, $user, $pwd))
        {
            $this->setError($this->CODE_FAIL, '连接客户端失败,请确认登陆信息');
            return false;
        }

        if (!ssh2_exec($this->conn, 'pwd'))
        {
            $this->setError($this->CODE_FAIL, '不能连接该主机');
            return false;
        }

        if(!ssh2_exec($this->conn,'which scp'))
        {
            $this->setError($this->CODE_FAIL, '该主机没有安装scp,请先安装');
            return false;
        }
    }

    /**
     * @name: 发送文件
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-06-13 16:42:12
     */
    function sendFile ($localPath, $remotePath)
    {
        $sftp = ssh2_sftp($this->conn);
        $srcFile = fopen($localPath, 'r');
        $resFile = fopen("ssh2.sftp://{$sftp}/" . $remotePath, 'w');
        
        $writtenBytes = stream_copy_to_stream($srcFile, $resFile);
        fclose($resFile);
        fclose($srcFile);
        // $stream = ssh2_scp_send($this->conn, $localPath, $remotePath, 0777);
    }

    /**
     * @name: 执行命令
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-06-13 16:46:21
     */
    function exec ($exec)
    {
        $stream = @ssh2_exec($this->conn , $exec);

        @ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
        @stream_set_blocking($stream,true);
        $return = @stream_get_contents($stream);
        @fclose($stream);

        return $return;
    }
}